import type { CodeQueryVO, Option } from '#/api';
import type { AsyncResult, DelayResult } from '#/utils/timeDelayReq';

import { ServicePrefixEnum } from '#/enums/commonEnum';
import { TimeDelayReq } from '#/utils/timeDelayReq';

import { requestClient } from '../request';

export interface SystemApiVO {
  springApplicationName: string;
  controller: string;
  name: string;
  requestMethod: string;
  uri: string;
}

export const findAll = () => {
  return requestClient.post<any>(
    `${ServicePrefixEnum.OAUTH}/anyUser/dict/enums/findAll`,
  );
};

/** 根据字典类型编码批量查询字典项 */
export const findDictMapByType = (params: CodeQueryVO[] = []) => {
  return requestClient.post<any>(
    `${ServicePrefixEnum.OAUTH}/anyUser/dict/findDictMapByType`,
    params,
  );
};

/** 根据字典类型编码查询字典项,并排除指定项 */
export const findDictByType = (params: CodeQueryVO) => {
  return requestClient.post<Option[]>(
    `${ServicePrefixEnum.OAUTH}/anyUser/dict/findDictByType`,
    params,
  );
};

/** 根据枚举类名批量查询枚举值列表 */
export const findEnumMapByType = (params: CodeQueryVO[]) => {
  return requestClient.post<any>(
    `${ServicePrefixEnum.OAUTH}/anyUser/enums/findEnumMapByType`,
    params,
  );
};

/** 根据枚举类名查询枚举值列表 */
export const findEnumByType = (params: CodeQueryVO) => {
  return requestClient.post<Option[]>(
    `${ServicePrefixEnum.OAUTH}/anyTenant/enums/findEnumByType`,
    params,
  );
};

export const findOnlineService = () => {
  return requestClient.get<Option[]>(
    `${ServicePrefixEnum.GATEWAY}/findOnlineService`,
  );
};

export const findOnlineServicePrefix = () => {
  return requestClient.get<any>(
    `${ServicePrefixEnum.GATEWAY}/findOnlineServicePrefix`,
  );
};

export const findSystemApi = (servicePrefix: string) => {
  return requestClient.get<Map<string, SystemApiVO[]>>(
    `/${servicePrefix}/anyone/systemApiScan`,
  );
};

const codeTimeDelayReq = new TimeDelayReq({
  cacheKey: (param) => `${param?.type}`,
  getErrorData(_param, error, _reject) {
    return {
      code: 400,
      msg: error.message || '请求错误',
      data: [],
    };
  },
  // 实现批量请求
  async api(paramList, cacheKey) {
    const data = await findDictMapByType(paramList);
    const resultMap: Map<string, DelayResult> = new Map<string, DelayResult>();
    paramList.forEach((param) => {
      const key = cacheKey(param);
      const dictList = data[param?.type];
      if (dictList) {
        resultMap.set(key, {
          key,
          isOk: true,
          data: {
            code: 0,
            data: dictList,
          },
        });
      }
    });
    return resultMap;
  },
});

export async function asyncFindDictList(
  param: CodeQueryVO,
): Promise<AsyncResult> {
  return codeTimeDelayReq.loadByParam(param);
}
